package com.qf.eduadmin.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author Mr.Liu
 * @date 2021/12/26 18:26
 */
@Controller
public class CaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    /**
     * 生成验证码的接口
     */
    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        byte[] chaptchaChallengAsJepg=null;

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        //使用kaptcha生成验证码
        String text = defaultKaptcha.createText();
        //将生成的验证码放置在session中
        request.getSession().setAttribute("captcha",text);
        //使用kaptcha生成图片
        BufferedImage image = defaultKaptcha.createImage(text);

        try {
            ImageIO.write(image,"jpg",byteArrayOutputStream);
            //将流对象转为字节流
            chaptchaChallengAsJepg = byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //定义response返回的类型为image/jpeg类型,使用response输出Byte数组
        response.setHeader("Cache-control","no-store");
        response.setHeader("Pragma","no-cache");
        response.setDateHeader("Expires",0);
        response.setContentType("image/jpeg");

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(chaptchaChallengAsJepg);
        outputStream.flush();
        outputStream.close();
    }
}
